import os,sys

def run_cmd(cmd):
	return ''.join(os.popen(cmd))

def depure(x):
	if x.endswith('\n'):
		return x[:-1]
	else:
		return x
	
def testFile(file):
	lines = []
	lines.extend(map(depure,open(file)))
	i = 0
	toRun = []
	for i in range(len(lines)):
		line = lines[i]
		if line.startswith('> '):
			cmd = line[2:]
			out = ''
			if i + 1 < len(lines):
				aux = lines[i+1]				
				if not aux.startswith('> '):
					i = i + 1
				while not aux.startswith('> ') and i < len(lines):
					out = out + aux + '\n'
					i = i + 1
					if i < len(lines):
						aux = lines[i]
			
			toRun.append(tuple([cmd,out]))
	
	fail = []
	d = 'test_'+file[:file.index('.')]
	os.mkdir(d)
	os.chdir(d)
	for cmd,expectedOut in toRun:
		realOut = run_cmd(cmd)
		if realOut != expectedOut or not realOut.startswith(expectedOut):
			fail.append(tuple([cmd,expectedOut,realOut]))
	os.chdir('..')
	if fail:
		for cmd,expected,real in fail:
			print "fail cmd '%s', expect '%s' and have '%s'" % (cmd,expected,real)
	else:
		print 'Complete success!!!'

def main():
	if len(sys.argv) == 2:
		file = sys.argv[1]
		if os.path.isfile(file):
			testFile(file)
		else:
			for file in filter(lambda x: x.endswith('.test'),os.listdir(file)):
				print 'testing', file,'...'
				testFile(file)
	else:
		print 'usage:\n python %s <file or dir>' % (__file__)
	

if __name__ == '__main__':
	main()